NET 2.0開始有這個功能,可以批次寫入.
我們做個簡單範例,把來源讀到的data table,新增到Target去.
建立測試資料表 source & target
--source
create table test_src
(
src1 int
,src2 int
,src3 int
)
insert into test_src select 1,1,1
insert into test_src select 2,2,2
insert into test_src select 3,3,3
--target
create table test_dest
(
COL1 int
,COL2 int
,COL3 int
)
執行
System.Data.DataTable dt = getsrc();//取來源
BulkCopy(dt);//寫入
取來源
private System.Data.DataTable getsrc()
{
System.Data.DataTable dt = new System.Data.DataTable();
string sConn = "data source = xxx ;initial catalog= db; user id = sa ;password= sa ";
using (SqlConnection conn = new SqlConnection(sConn))
{
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter("select * from test_src", conn);
adp.Fill(dt);
}
return dt;
}
寫入
private void BulkCopy( System.Data.DataTable dt)
{
// 整批轉入
string sConn = "data source = xxx ;initial catalog= db; user id = sa ;password= sa ";
using (SqlConnection conn = new SqlConnection(sConn))
{
conn.Open();
using (SqlBulkCopy sqlBC = new SqlBulkCopy(conn))
{
//設定一個批次量寫入多少筆資料
sqlBC.BatchSize = 1000;
//設定逾時的秒數
sqlBC.BulkCopyTimeout = 60;
//設定要寫入的資料庫
sqlBC.DestinationTableName = "test_dest";
//對應資料行
sqlBC.ColumnMappings.Add("src1", "COL1");
sqlBC.ColumnMappings.Add("src2", "COL2");
sqlBC.ColumnMappings.Add("src3", "COL3");
//開始寫入
sqlBC.WriteToServer(dt);
}
}
}
對應資料行的部分,也可以把dt的改成和dest一樣,這樣ColumnMappings就不用因不同的來源,而變動.
dt.Columns[0].ColumnName = "COL1";
dt.Columns[1].ColumnName = "COL2";
dt.Columns[2].ColumnName = "COL3";
ref
https://dotblogs.com.tw/supershowwei/2016/12/09/221622
取來源
private System.Data.DataTable getsrc()
{
System.Data.DataTable dt = new System.Data.DataTable();
string sConn = "data source = xxx ;initial catalog= db; user id = sa ;password= sa ";
using (SqlConnection conn = new SqlConnection(sConn))
{
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter("select 1,2,3", conn);
adp.Fill(dt);
}
return dt;
}
private void BulkCopy( System.Data.DataTable dt)
{
// 整批轉入
string sConn = "data source = xxx ;initial catalog= db; user id = sa ;password= sa ";
using (SqlConnection conn = new SqlConnection(sConn))
{
conn.Open();
using (SqlBulkCopy sqlBC = new SqlBulkCopy(conn))
{
//設定一個批次量寫入多少筆資料
sqlBC.BatchSize = 1000;
//設定逾時的秒數
sqlBC.BulkCopyTimeout = 60;
//設定要寫入的資料庫
sqlBC.DestinationTableName = "test_dest";
//開始寫入
sqlBC.WriteToServer(dt);
}
}
}
https://blog.gss.com.tw/index.php/2018/08/08/sqlbulkcopy/